import random

from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from syl import settings
from user.models import User
from user.sers import UserSerializer
from user.utils import validateEmail, validatePassword
from redis import StrictRedis
from django.core.mail import send_mail


# 发邮件接口
class EmailView(APIView):
    def post(self, request):
        # 1. 接收邮箱
        data = request.data
        email = data.get('email')
        # 2. 验证邮箱格式
        if validateEmail(email):
            pass
        else:
            return Response({'code': 999, 'msg': '邮箱格式错误'})
        # 3. 生成验证码, 随机数
        code = '%06d' % random.randint(0, 999999)  # 需要一个6位的验证码
        # 4. 保存到redis
        redis_client = StrictRedis()
        redis_client.set(email, code)
        # 5. 发送邮箱  subject 主题, message 内容, from_email 谁发的邮件, recipient_list  [接收人],
        send_mail(
            subject='实验楼验证邮件',
            message='您的验证码是%s' % code,
            from_email=settings.EMAIL_FROM,
            recipient_list=[email]
        )
        # 6. 返回响应
        return Response({'code': 0, 'msg': '邮件发送成功'})


class RegisterView(APIView):
    def post(self, requset):
        # 1. 接收数据, 邮箱, 密码, 验证码
        data = requset.data
        email = data.get('user_email')
        password = data.get('password')
        email_code = data.get('email_code')

        # 2. 非空验证, 验证密码, 验证code
        if all([email, password, email_code]):
            pass
        else:
            return Response({'code': 999, 'msg': '缺少参数'})
        if validatePassword(password):
            pass
        else:
            return Response({'code': 999, 'msg': '密码格式错误'})
        redis_client = StrictRedis()
        redis_email_code = redis_client.get(email)  # 返回来的是None 或者 bytes
        if redis_email_code:
            redis_email_code = redis_email_code.decode()
        if email_code == redis_email_code:
            pass
        else:
            return Response({'code': 999, 'msg': '邮箱验证码错误'})
        # 3. 注册用户, 用户名使用邮箱
        # User.objects.create(username=email, password=password, email=email) # 不加密密码
        try:
            User.objects.create_user(username=email, password=password, email=email)  # 加密密码
        except Exception as e:
            return Response({'code': 999, 'msg': '注册失败,数据库错误'})
        # 4. 返回注册成功
        return Response({'code': 0, 'msg': '注册成功'})


class UserModelViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# restful,   处理模型, 时的规范,  url的写法,  ->   模型的操作,
# /user/get/?id=123   ->
# 获取一个   GET /user/123/
# 获取多个   GET /user/
# 创建一个   POST /user/  body{'username':'lisi', 'password':'xxxx'}
# 修改一个   PUT  /user/1/  body{'username':'lisi', 'password':'xxxx'}
# 删除一个   DELETE  /user/1/


# 用在处理数据, 大幅度增加我们的数据操作接口的开发效率,   提高代码的健壮性(...), 鲁棒性

# 1. 数据接口,   对数据进行增删改查
# 2. 业务接口,   发送短信,  调用三方接口,  数据存redis,  apiview